package com.zmn.oms.business.impl.member;

import org.apache.dubbo.config.annotation.Reference;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.map.Point;
import com.zmn.common.utils.math.MoneyUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.dms.dubbo.constant.DmsDubboConsts;
import com.zmn.dms.dubbo.interfaces.coup.coupon.CoupGetRemoteService;
import com.zmn.oms.business.interfaces.member.OrderMemberBService;
import com.zmn.oms.business.interfaces.messageV1.text.MessageSendTextService;
import com.zmn.oms.business.interfaces.orderamount.OrderAmountCalcBService;
import com.zmn.oms.business.interfaces.work.OrderWorkAmountBService;
import com.zmn.oms.common.annotation.ZsNormalOrderWorkLog;
import com.zmn.oms.common.constant.MessageRuleIdConsts;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderLogConsts;
import com.zmn.oms.common.constant.TriggerAmountChangeEnum;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.bo.orderamount.OrderAmountCalcBO;
import com.zmn.oms.model.bo.orderamount.ReCalcOrderAmountDIO;
import com.zmn.oms.model.dto.member.CouponDTO;
import com.zmn.oms.model.dto.member.OrderMemberMasterReviewDTO;
import com.zmn.oms.model.dto.member.OrderMemberPlatReviewDTO;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.member.OrderMember;
import com.zmn.oms.model.entity.warranty.OrderWarranty;
import com.zmn.oms.model.entity.warranty.OrderWarrantyProduct;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.vo.member.OrderMemberPlatReviewVO;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.member.OrderMemberService;
import com.zmn.oms.services.interfaces.warranty.OrderWarrantyProductService;
import com.zmn.oms.services.interfaces.warranty.OrderWarrantyService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.pay.common.constant.PayConsts;
import com.zmn.vas.common.dro.order.CoupInfoDRO;
import com.zmn.vas.common.dro.order.ExtendedWarrantyDRO;
import com.zmn.vas.dubbo.consts.VasDubboConsts;
import com.zmn.vas.dubbo.interfaces.order.VasOrderListRemoteService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 类描述：会员审核
 *
 * @author lujia
 * @date 2018/12/19 15:30
 */
@Service
public class OrderMemberBServiceImpl implements OrderMemberBService {

    @Autowired
    OrderMemberService orderMemberService;
    @Autowired
    OrderWorkService orderWorkService;
    @Reference(version = VasDubboConsts.INTERFACE_VERSION, check = false)
    private VasOrderListRemoteService vasOrderListRemoteService;
    @Autowired
    private MessageSendTextService messageSendTextService;
    @Reference(version = DmsDubboConsts.INTERFACE_VERSION, check = false)
    private CoupGetRemoteService coupGetRemoteService;
    @Autowired
    OrderAmountCalcBService orderAmountCalcBService;
    @Autowired
    OrderWorkAmountBService orderWorkAmountBService;
    @Autowired
    OrderWarrantyService orderWarrantyService;
    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    OrderWarrantyProductService orderWarrantyProductService;
    private static final Logger logger = LoggerFactory.getLogger(OrderMemberBServiceImpl.class);

    @Override
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_MEM_PLAT_REVIEW)
    @Transactional
    public boolean savePlatReview(OrderMemberPlatReviewDTO platReviewDTO) throws OmsBaseException {

        OrderMember orderMember = BeanMapper.map(platReviewDTO, OrderMember.class);
        orderMember.setMemberOrderId(platReviewDTO.getOrderId());

        // 整机 审核结果
        Integer platReviewDeviceResult = platReviewDTO.getPlatReviewDeviceResult();
        // 易碎贴 审核结果
        Integer platReviewFragilePasteResult = platReviewDTO.getPlatReviewFragilePasteResult();
        // 铭牌 审核结果
        Integer platReviewNameplateResult = platReviewDTO.getPlatReviewNameplateResult();

        boolean device = Objects.equals(OrderConsts.ORDER_MEMBER_REVIEW_RESULT_SUCCESS, platReviewDeviceResult);
        boolean fragilePaste = Objects.equals(OrderConsts.ORDER_MEMBER_REVIEW_RESULT_SUCCESS, platReviewFragilePasteResult);
        boolean nameplate = Objects.equals(OrderConsts.ORDER_MEMBER_REVIEW_RESULT_SUCCESS, platReviewNameplateResult);
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(platReviewDTO.getOrderId(), platReviewDTO.getWorkId());

        OrderWork updateOrderWork = new OrderWork();
        updateOrderWork.setWorkId(orderWork.getWorkId());
        updateOrderWork.setOrderId(orderWork.getOrderId());

        // 有一个审核不通过则审核结果为审核失败
        boolean reviewSuccess = device && fragilePaste && nameplate;
        if (reviewSuccess) {
            orderMember.setReviewResult(OrderConsts.ORDER_MEMBER_REVIEW_RESULT_SUCCESS);
            orderMember.setReviewStatus(OrderConsts.ORDER_MEMBER_REVIEW_STATUS_PLAT_SUCCESS);
            updateOrderWork.setMember(GlobalConsts.YES);
        } else {
            orderMember.setReviewResult(OrderConsts.ORDER_MEMBER_REVIEW_RESULT_FAIL);
            orderMember.setReviewStatus(OrderConsts.ORDER_MEMBER_REVIEW_STATUS_PLAT_FAIL);
            updateOrderWork.setMember(GlobalConsts.NO);
        }

        orderMember.setPlatReviewTime(DateUtil.getNow());
        orderMemberService.updatePlatReview(orderMember);

        // 设为延保单
        orderWorkService.updateOrderWorkByKey(updateOrderWork);

        if (reviewSuccess) {
            orderMember = orderMemberService.findMemberByKey(platReviewDTO.getOrderId());
            ResponseDTO<ExtendedWarrantyDRO> extendedWarrantyInfoByRespDTO = vasOrderListRemoteService.getExtendedWarrantyInfoByCode(orderMember.getFragileCode(), orderWork.getWorkId());
            ExtendedWarrantyDRO extendedWarranty = extendedWarrantyInfoByRespDTO.getData();
            logger.info("延保审核信息:extendedWarranty:{}", extendedWarranty);
            if (Objects.isNull(extendedWarranty)) {
                throw new OmsBaseException("获取延保信息失败！");
            }

            //剩余可用维修金额
            int totalAvailableAmount = 0;
            int discountAmount = 0;
            int masterAmount = 0;
            List<CoupInfoDRO> coupInfoDROList = extendedWarranty.getCoupInfoDROList();
            if (CollectionUtils.isNotEmpty(coupInfoDROList)) {
                CoupInfoDRO coupInfoDRO = coupInfoDROList.get(0);

                // 核销优惠券(计算和更新工单金额)
                ReCalcOrderAmountDIO calcOrderAmountDIO = orderAmountCalcBService.getReCalcOrderAmountDIO(orderWork);
                calcOrderAmountDIO.setInvoker(2);
                calcOrderAmountDIO.setCouponCode(coupInfoDRO.getCouponCode());
                OrderAmountCalcBO orderAmountCalcBO = orderAmountCalcBService.reCalcOrderAmountAndDiscountAmount(TriggerAmountChangeEnum.EXTENDED_WARRANTY, calcOrderAmountDIO, null);
                orderWorkAmountBService.updateAmountAndDiscount(orderAmountCalcBO, orderWork);

                discountAmount = orderAmountCalcBO.getDiscountAmount() == null ? 0 : orderAmountCalcBO.getDiscountAmount();
                totalAvailableAmount = coupInfoDRO.getAmount() - orderWork.getOriginalAmount();
                totalAvailableAmount = totalAvailableAmount < 0 ? 0 : totalAvailableAmount;
                masterAmount = Objects.isNull(orderAmountCalcBO.getMasterAmount()) ? 0 : orderAmountCalcBO.getMasterAmount();
                logger.info("使用优惠券码:{}, 优惠信息:{}", coupInfoDRO.getCouponCode(), orderAmountCalcBO);
            }

            // 服务总价-----原价
            String originalAmountStr = MoneyUtil.parseToYuan(orderWork.getOriginalAmount()).toString();
            // 成功使用维修金----优惠金额
            String discountAmountStr = MoneyUtil.parseToYuan(discountAmount).toString();
            // 应收-----应收总额(工程师收款额)
            String masterAmountStr = MoneyUtil.parseToYuan(masterAmount).toString();
            // 剩余可用维修金-----剩余现金卡金额
            String totalAvailableAmountStr = MoneyUtil.parseToYuan(totalAvailableAmount).toString();

            // 审核通过给用户发送短信
            OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(orderWork.getOrderId());

            Map<String, String> smsMap = new HashMap<>();
            smsMap.put("amount",originalAmountStr);
            smsMap.put("maintain_costs",discountAmountStr);
            smsMap.put("payment",masterAmountStr);
            smsMap.put("maintain_rest",totalAvailableAmountStr);
            messageSendTextService.sendTextMessage(MessageRuleIdConsts.ZMN_MSG_RULEID_PLATREVIEW, orderDetail.getTelephone(), smsMap);
        }
        return reviewSuccess;
    }

    @Override
    public OrderMemberPlatReviewVO findPlatReviewVO(Long orderId, Long workId)
            throws OmsBaseException {

        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
        OrderMember orderMember = orderMemberService.findMemberByKey(orderId);

        String electrFragileCode = orderMember.getFragileCode();
        ResponseDTO<ExtendedWarrantyDRO> extendedWarrantyInfoByRespDTO = vasOrderListRemoteService.getExtendedWarrantyInfoByCode(electrFragileCode, orderWork.getWorkId());
        if (Objects.isNull(extendedWarrantyInfoByRespDTO)) {
            throw new OmsBaseException("获取延保信息失败！");
        }

        OrderMemberPlatReviewVO vo = new OrderMemberPlatReviewVO();
        BeanMapper.copy(orderWork, vo);
        BeanMapper.copy(orderMember, vo);

        Integer prepayAmount = GlobalConsts.NONE;
        if (orderWork.getPrepayStatus() == PayConsts.PAY_STATUS_DONE) {
            prepayAmount += orderWork.getPrepayAmount();
        }
        if (orderWork.getDepositStatus() == PayConsts.PAY_STATUS_DONE) {
            prepayAmount += orderWork.getDepositAmount();
        }
        if (orderWork.getChannelPrepayStatus() == PayConsts.PAY_STATUS_DONE) {
            prepayAmount += orderWork.getChannelPrepayAmount();
        }
        vo.setPrepayAmount(prepayAmount);

        if (!Objects.isNull(extendedWarrantyInfoByRespDTO.getData())) {
            ExtendedWarrantyDRO extendedWarrantyDRO = extendedWarrantyInfoByRespDTO.getData();
            OrderWarranty orderWarranty = orderWarrantyService.findByOrderId(extendedWarrantyDRO.getWorkId());
            if (!Objects.isNull(orderWarranty)) {
                boolean orderWarrantyStatusValid = Objects.equals(OrderConsts.ORDER_WARRANTY_STATUS_VALID, orderWarranty.getStatus());
                if (orderWarrantyStatusValid) {
                    vo.setStartTime(orderWarranty.getEffectiveTime());
                }
            }

            List<OrderWarrantyProduct> orderWarrantyProductList = orderWarrantyProductService.listByOrderId(extendedWarrantyDRO.getWorkId());
            logger.info("orderId:{},workId:{},orderWarranty:{},orderWarrantyProductList:{}",orderId,workId,orderWarranty,orderWarrantyProductList);
            if (CollectionUtils.isNotEmpty(orderWarrantyProductList)) {
                OrderWarrantyProduct orderWarrantyProduct = orderWarrantyProductList.get(0);
                if (null != orderWarrantyProduct && null != orderWarrantyProduct.getExpiredTime()) {
                    vo.setEndTime(orderWarrantyProduct.getExpiredTime());
                }
            }
        }

        ExtendedWarrantyDRO extendedWarranty = extendedWarrantyInfoByRespDTO.getData();
        if (null != extendedWarranty) {
            List<CoupInfoDRO> coupInfoDROList = extendedWarranty.getCoupInfoDROList();
            if (null != coupInfoDROList && GlobalConsts.NONE != coupInfoDROList.size()) {
                CoupInfoDRO coupInfoDRO = coupInfoDROList.get(GlobalConsts.NONE);
                vo.setCoupon(BeanMapper.map(coupInfoDRO, CouponDTO.class));//获取单个优惠券信息
            }
            vo.setUserDeviceImageSrc(extendedWarranty.getElectrSrc());
            vo.setUserFragilePasteImageSrc(extendedWarranty.getElectrFragileSrc());
            vo.setUserNameplateImageSrc(extendedWarranty.getElectrNameplateSrc());
        }

         Double masterReviewLatitude = orderMember.getMasterReviewLatitude();
         Double masterReviewLongitude = orderMember.getMasterReviewLongitude();
         vo.setMasterPoint(new Point(masterReviewLongitude, masterReviewLatitude));

        // String lat = memOrderAuthDRO.getRegLatitude();
        // String lng = memOrderAuthDRO.getRegLongitude();
        // vo.setUserPoint(new Point(Double.parseDouble(lng), Double.parseDouble(lat)));

        //double lat1, double lng1, double lat2, double lng2
        // Point userPoint = vo.getUserPoint();
        // Point masterPoint = vo.getMasterPoint();
        // if (userPoint != null && masterPoint != null) {
        //     double distance = MapUtils.getDistance(
        //             userPoint.getLat(), userPoint.getLng(),
        //             masterPoint.getLat(),masterPoint.getLng());
        //     vo.setDistance(distance);
        // }

        return vo;
    }

    @Override
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_MEM_MASTER_REVIEW)
    @Transactional
    public boolean saveMasterReview(OrderMemberMasterReviewDTO mastertReviewDTO) {
        OrderMember orderMember = BeanMapper.map(mastertReviewDTO, OrderMember.class);
        orderMember.setMemberOrderId(mastertReviewDTO.getOrderId());

        // 工程师是否审核成功
        boolean reviewSuccess = Objects.equals(OrderConsts.ORDER_MEMBER_REVIEW_RESULT_SUCCESS,mastertReviewDTO.getMasterReviewResult());

        // 是否是延保电器
        boolean notExtendedWarrnty = Objects.equals(OrderConsts.ORDER_MEMBER_REVIEW_RESULT_NOT_EXTENDEDWARRANTY,mastertReviewDTO.getMasterReviewResult());

        // 有一个审核不通过则审核结果为审核失败
        if (reviewSuccess) {
            orderMember.setReviewResult(OrderConsts.ORDER_MEMBER_REVIEW_RESULT_DOING);
            orderMember.setReviewStatus(OrderConsts.ORDER_MEMBER_REVIEW_STATUS_WAIT_PLAT);
            orderMember.setVerify(GlobalConsts.YES);
        } else if (notExtendedWarrnty) {
            orderMember.setReviewResult(OrderConsts.ORDER_MEMBER_REVIEW_RESULT_NOT_EXTENDEDWARRANTY);
            orderMember.setReviewStatus(OrderConsts.ORDER_MEMBER_REVIEW_STATUS_MASTER_FAIL);
            orderMember.setVerify(GlobalConsts.NO);
        } else {
            orderMember.setReviewResult(OrderConsts.ORDER_MEMBER_REVIEW_RESULT_FAIL);
            orderMember.setReviewStatus(OrderConsts.ORDER_MEMBER_REVIEW_STATUS_MASTER_FAIL);
            orderMember.setVerify(GlobalConsts.NO);
        }

        orderMember.setMasterReviewTime(DateUtil.getNow());

        OrderMember existOrderMember = orderMemberService.findMemberByKey(mastertReviewDTO.getOrderId());
        if (null == existOrderMember) {
            orderMemberService.insertOrderMember(orderMember);
        } else {
            orderMemberService.updateMasterReview(orderMember);
        }

        return reviewSuccess;
    }

    /**
     * @descript :判断是延保订单,且全额使用了优惠券
     * @author : xiaofei
     * @param : orderId, workId
     * @return : boolean
     * @date : 2020/7/16
     * @version : v1.0
     */
    @Override
    public boolean verifyOrderMemberAndDiscount(Long orderId, Long workId) {
        boolean isMember = false;
        boolean fullDiscount = false;

        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
        if (!Objects.isNull(orderWork)) {
            fullDiscount = Objects.equals(orderWork.getTotalAmount(), 0);
            OrderMember orderMember = orderMemberService.findMemberByKey(orderId);
            isMember = orderWork.getMember() == GlobalConsts.YES
                    && orderMember.getReviewResult() == OrderConsts.ORDER_MEMBER_REVIEW_RESULT_SUCCESS
                    && orderMember.getReviewStatus() == OrderConsts.ORDER_MEMBER_REVIEW_STATUS_PLAT_SUCCESS;
        }

        return isMember && fullDiscount ;
    }
}
